package com.example.backend.service.mysql.user.impl;

import com.example.backend.dto.RegisterDto;
import com.example.backend.entitly.mysql.user.Users;
import com.example.backend.service.mysql.permission.RolesService;
import com.example.backend.service.mysql.permission.UserRolesService;
import com.example.backend.service.mysql.user.AuthMethodService;
import com.example.backend.service.mysql.user.UserAuthService;
import com.example.backend.service.mysql.user.UserRegisterService;
import com.example.backend.service.mysql.user.UsersService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class UserRegisterServiceImpl implements UserRegisterService {

    private final RolesService roleService;
    private final UserAuthService userAuthService;
    private final UserRolesService userRolesService;
    private final UsersService usersService;
    private final AuthMethodService authMethodService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean passwordRegister(RegisterDto registerDto) {
        Users users = usersService.saveByUser(registerDto.getUsername());
        Integer byDefaultName = roleService.getByDefaultName();
        boolean b = userRolesService.savaByUser(users.getUserId(), byDefaultName);
        if (!b) {
            return false;
        }
        Integer authId = authMethodService.getByCode("password");
        return userAuthService.savaByUser(registerDto.getUsername(), registerDto.getPassword(), users.getUserId(), authId);
    }
}
